import { _decorator, Component, director, tween } from 'cc';
import TurkishTetris_CardFunctions from "../Common/TurkishTetris_CardFunctions";
import { TurkishTetris_GameData } from "../../../../hall/Data/TurkishTetris_GameData";
import TurkishTetris_GamePanel from "../UI/TurkishTetris_GamePanel";
import TurkishTetris_MapManager from "./TurkishTetris_MapManager";
import { TurkishTetris_FloorTipCom } from "../Game/TurkishTetris_FloorTipCom";
import TurkishTetris_GameConfig from "../../../../hall/Data/TurkishTetris_GameConfig";
import UI from "../../../../../../Script/Manager/UI";
import SSS_TimerManager from "../../../../../../Script/Manager/SSS_TimerManager";
import TurkishTetris_LosePanel from "../UI/TurkishTetris_LosePanel";
import { TurkishTetris_GameStorage } from "../../../../hall/Data/TurkishTetris_GameStorage";

const { ccclass, property, executionOrder } = _decorator;

// /** GameManager */
// // 慢一点执行
@ccclass('TurkishTetrisGameManager')
@executionOrder(101)
export default class TurkishTetris_GameManager extends Component {
        static Instance: TurkishTetris_GameManager;
        @property({ type: TurkishTetris_FloorTipCom })
        floorTipCom: TurkishTetris_FloorTipCom = null;
        onLoad() {
                TurkishTetris_GameManager.Instance = this;

                // XXL_GameEventManager.AddListener();

                UI.Instance.ResetUINode();

                this.Init();
        }
        async Init() {
                TurkishTetris_GameStorage.initData();

                // GameStorage.initData();
                TurkishTetris_GameData.InitData();

                this.scheduleOnce(() => {
                        TurkishTetris_MapManager.Instance.initCard();
                        TurkishTetris_GamePanel.Instance.ShowOn();
                }, 0.2);
        }
        //    // 当前用到标识 12
        static Main(step: any) {
                // xwLog("call Main step", step);
                // 下落
                if (TurkishTetris_CardFunctions.GetHasNotFallCardAll()) {
                        TurkishTetris_GameManager.Instance.scheduleOnce(() => {
                                TurkishTetris_CardFunctions.AllBlockFallToCanNotFall();
                                TurkishTetris_GameManager.Main(1);
                        }, 0.1);
                }
                // // 三消
                else if (TurkishTetris_CardFunctions.IsHasAllClear()) {
                        TurkishTetris_GameManager.Instance.scheduleOnce(() => {
                                TurkishTetris_CardFunctions.ClearAllRow();
                                // XXL_GameManager.Main();
                        }, 0.1);
                }
                // 其他
                else {
                        if (
                                TurkishTetris_GameData.gameMode == 0 &&
                                TurkishTetris_CardFunctions.GetRowNumber() < TurkishTetris_GameConfig.row &&
                                (TurkishTetris_GameData.hasNewLine === false || TurkishTetris_CardFunctions.GetRowNumber() < TurkishTetris_GameData.GetMinRowNumber())
                        ) {
                                TurkishTetris_GameManager.Instance.scheduleOnce(() => {
                                        // if (GameData.IsDead()) {
                                        //     XXL_GameManager.Dead();
                                        // }

                                        // else{
                                        if (TurkishTetris_GameStorage.data.GameData.roundNumber > 0) {
                                                TurkishTetris_GameStorage.data.GameData.roundNumber--;

                                                TurkishTetris_GamePanel.Instance.chainNumTxt.string = TurkishTetris_GameStorage.data.GameData.roundNumber;
                                                if (TurkishTetris_GameStorage.data.GameData.roundNumber == 0) {
                                                        // XXL_GamePanel.Instance.hideChainAnim();
                                                }

                                                TurkishTetris_GameStorage.saveData();
                                        } else {
                                                TurkishTetris_CardFunctions.MoveAllRow(+1);
                                                TurkishTetris_CardFunctions.NewLineBlock_0();
                                                TurkishTetris_CardFunctions.NewLineBlock_next();
                                                TurkishTetris_GameManager.Instance.floorTipCom.showFloorTip();
                                        }

                                        TurkishTetris_GameData.hasNewLine = true;
                                        TurkishTetris_GameManager.Instance.scheduleOnce(() => {
                                                TurkishTetris_GameManager.Main(2);
                                        }, 0.1);

                                        // GameStorage.ArrCardGroupsToMapData();
                                        // }
                                }, 0.2);
                        } else {
                                // GameData.hasNewLine = false;
                                // GameData.IsCanOperate = true;
                                // GameData.ContinuousEliminationNumber = 0;

                                // GameStorage.ArrCardGroupsToMapData();

                                // XXL_GamePanel.Instance.Refresh();

                                // console.log(`回合结束`);

                                TurkishTetris_GameManager.RoundEnd();

                                if (TurkishTetris_GameData.gameMode == 0) {
                                        console.log(`TurkishTetris_GameData.IsDead()`, TurkishTetris_GameData.IsDead());
                                        if (TurkishTetris_GameData.IsDead()) {
                                                TurkishTetris_GameManager.Dead();
                                                return;
                                        }

                                        // if (GameData.IsAssistance()) {
                                        //     // XXL_GameManager.Assistance();
                                        // }
                                } else if (TurkishTetris_GameData.gameMode == 1) {
                                        // if (GameData.IsDesertWin()) {
                                        //     XXL_GamePanel.Instance.timeProgress.pause();
                                        //     GameData.desertGameUseTime = XXL_GamePanel.Instance.timeProgress.getUsedTime();
                                        //     XXL_GameManager.Instance.scheduleOnce(() => {
                                        //         XXL_GameManager.DesertWin();
                                        //     }, 0.5);
                                        //     return;
                                        // }
                                }
                                // XXL_TipPanel.Instance.Show(`回合结束`);
                        }
                }
        }
        static Dead() {
                // if (TurkishTetris_GameStorage.data.GameData.deadCount === 0) {
                //     let data = {
                //         callback_ok: () => {
                //             TurkishTetris_GameManager.Reborn();
                //         },
                //         callback_close: () => {
                //             TurkishTetris_GameManager.GameOverAnimation();
                //         },
                //     };
                // hallFunc.showPanel(HallResConstant.PREFABS_PATH.RebornPanel, data);
                // } else {
                TurkishTetris_GameManager.GameOverAnimation();
                // }

                TurkishTetris_GameStorage.data.isEnd = true;
                // TurkishTetris_GameStorage.saveData();

                TurkishTetris_GameStorage.data.GameData.deadCount++;
                TurkishTetris_GameStorage.saveData();
        }
        //    /** 复活 */
        static Reborn() {
                TurkishTetris_GameStorage.data.isEnd = false;
                TurkishTetris_GameStorage.saveData();


                TurkishTetris_CardFunctions.ToColor();

                TurkishTetris_CardFunctions.ClearOneRow(0);
                TurkishTetris_CardFunctions.ClearOneRow(1);
                TurkishTetris_CardFunctions.ClearOneRow(2);
                TurkishTetris_GameManager.Main(3);
        }
        //    /** 新的一局 */
        static NewGame() {
                TurkishTetris_GameStorage.data.GameData = {};
                TurkishTetris_GameStorage.data.GameData.IsGameOn = true;
                // TurkishTetris_GameStorage.data.GameData.score = 0;
                TurkishTetris_GameStorage.data.GameData.level = 0;
                TurkishTetris_GameStorage.data.GameData.deadCount = 0;
                TurkishTetris_GameStorage.data.GameData.assistanceCount = 0;
                TurkishTetris_GameStorage.data.GameData.roundNumber = 0;
                TurkishTetris_GameStorage.data.GameData.clearRowNumber = 0;
                TurkishTetris_GameStorage.data.GameData.isHasSkill = false;

                TurkishTetris_GameStorage.data.GameData.mapData = {};
                TurkishTetris_GameStorage.data.GameData.mapData_next = [];

                TurkishTetris_GameStorage.data.isEnd = false;
                TurkishTetris_GameStorage.data.score = 0;

                TurkishTetris_GameStorage.saveData();

                TurkishTetris_CardFunctions.NewLineBlock_next();
                // CardFunctions.NewLineBlock(0);
                // CardFunctions.NewLineBlock(1);
                // CardFunctions.NewLineBlock(2);

                TurkishTetris_GameManager.Main(4);
        }
        //    /** 游戏结束动画 */
        static async GameOverAnimation() {
                // XXL_GameManager.GameOver();
                // return

                // let rowNumber = CardFunctions.GetRowNumber();

                // for (let y = 0; y < GameData.arrCardGroups.length; y++) {
                //     const row = GameData.arrCardGroups[y];

                // let y = 0;
                // let fun = () => {
                //     const row = GameData.arrCardGroups[y];

                //     let count = 0;
                //     XXL_GameManager.Instance.scheduleOnce(() => {
                //         y++;
                //         for (let index = 0; index < row.length; index++) {
                //             const cardGroup: CardGroup = row[index];
                //             cardGroup.ToGray();
                //             count++;
                //             if (count >= row.length - 1) {
                //                 if (y >= rowNumber) {
                //                     XXL_GameManager.Instance.scheduleOnce(() => {
                //                         XXL_GameManager.GameOver();
                //                     }, 0.4);
                //                 } else {
                //                     fun();
                //                 }
                //             }
                //         }
                //     }, 1 * 0.3);
                // };

                // fun();

                TurkishTetris_GameData.IsCanOperate = false;
                let interval = 0.2;
                let keepTime = 0.4;
                for (let index = 0; index < TurkishTetris_GameConfig.row; index++) {
                        const row = TurkishTetris_GameData.arrCardGroups[index];
                        for (const cardGroup of row) {
                                tween(cardGroup.node)
                                        // .delay((index + 1) * interval)
                                        .call(() => {
                                                cardGroup.ToGray();
                                        })
                                        .start();

                                await SSS_TimerManager.AwaitTime(0.05);
                        }
                }


                await SSS_TimerManager.AwaitTime(0.1);
                // UI.Instance.CreatePanel(`UI/FailPanel`, FailPanel);
                // UI.Instance.CreatePanel_sub(`UI/FailPanel`, FailPanel);

                UI.Instance.CreatePanel_sub(`TurkishTetris_Prefab`, `UI/TurkishTetris_LosePanel`, TurkishTetris_LosePanel);


                // XXL_GameManager.Instance.scheduleOnce(() => {
                //     // XXL_GameManager.GameOver();
                // }, keepTime + XXL_GameConfig.row * interval);

                // AudioPlayer.getInstance().playSound("sound/lose", false, hallFunc.xwResBundle);

                // XXL_GamePanel.Instance.blockBgNode.active = true;
        }
        //    /** 回合结束 */
        static RoundEnd() {
                TurkishTetris_GameData.hasNewLine = false;
                TurkishTetris_GameData.IsCanOperate = true;
                TurkishTetris_GameData.ContinuousEliminationNumber = 0;

                TurkishTetris_GameStorage.ArrCardGroupsToMapData();

                TurkishTetris_GamePanel.Instance.Refresh();

                // console.log(`回合结束`);
                // XXL_TipPanel.Instance.Show(`回合结束`);
        }
        //    /** 加载主场景 */
        static LoadMainScene() {
                // GameData.ClearData();
                // SceneManager.getInstance().loadSceneWithBundle(BundleType.Hall, SceneConst.SCENE_NAME.main, { forceLoadScene: true });
        }
        ReStart() {
                TurkishTetris_GameStorage.data.isEnd = true;
                TurkishTetris_GameStorage.saveData();

                let currentSceneName = director.getScene().name;
                director.loadScene(currentSceneName);

                // if (fromGame) {
                //     LocalStorage.getInstance().setInt(HallConst.LocalStorageKey.curScore, 0);
                //     GameStorage.data.GameData = {};
                //     GameStorage.saveData();
                // }
                // GameData.ClearData();
                // XXL_GamePanel.Instance.ShowOff();

                // SceneManager.getInstance().loadSceneWithBundle(BundleType.Game, SceneConst.SCENE_NAME.game, { forceLoadScene: true });
        }
        static SaveMapData() {
                TurkishTetris_GameStorage.data.GameData.mapData = {};
                TurkishTetris_GameStorage.saveData();
        }
}

// /** 调试 */
window["TurkishTetris_GameManager"] = TurkishTetris_GameManager;